package com.da.lon.wang.xlg.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.da.lon.wang.xlg.MyApplication;
import com.da.lon.wang.xlg.R;
import com.da.lon.wang.xlg.adapter.SkuListAdapter;
import com.da.lon.wang.xlg.bean.SkuListResult;
import com.da.lon.wang.xlg.bean.SkuListResult.SkuInfo;
import com.da.lon.wang.xlg.constants.XLGConstants;
import com.da.lon.wang.xlg.http.HttpLoader;
import com.da.lon.wang.xlg.http.HttpLoader.OnWebLoadListener;
import com.da.lon.wang.xlg.pulltorefresh.library.PullToRefreshListView;
import com.da.lon.wang.xlg.util.BuyUtil;
import com.da.lon.wang.xlg.util.ToastUtils;
import com.da.lon.wang.xlg.util.Utils;
import com.da.lon.wang.xlg.util.XLGDataUtils;
import com.umeng.analytics.MobclickAgent;
import com.zxing.android.CaptureActivity;

import net.tsz.afinal.http.AjaxParams;

/**
 * 第一次进入选择SKU(体验店)类
 *
 * @author chencong
 */
public class ChoessSKUListActivity extends BaseActivity implements
        OnClickListener, AMapLocationListener {

    TextView title;
    ImageButton left;
    PullToRefreshListView listView;
    BuyUtil util;
    private ImageView ocoffee_top_right;
    private TextView sku_address_tv;
    private ImageView ocoffee_top_left;
    private ImageView sku_list_network_img;
    Handler mHandler = new Handler() {
        public void dispatchMessage(android.os.Message msg) {
            switch (msg.what) {
                case Utils.MSG_LOCATION_START:
                    sku_address_tv.setText("正在定位...");
                    showDialog();
                    break;
                case Utils.MSG_LOCATION_FINISH:
                    StringBuffer sb = new StringBuffer();
                    AMapLocation loc = (AMapLocation) msg.obj;
                    if (null != loc && loc.getErrorCode() == 0) {
                        sku_address_tv.setText(loc.getCity());
                        ocoffee_top_left.setEnabled(false);
                    } else {
                        ocoffee_top_left.setEnabled(true);
                        sku_address_tv.setText("定位失败");
                        ToastUtils.showShort(ChoessSKUListActivity.this, "定位失败！");
                    }
                    getData(loc.getLatitude(), loc.getLongitude());
                    break;
                case Utils.MSG_LOCATION_STOP:
                    break;
                default:
                    break;
            }
        }

        ;
    };
    private RelativeLayout home_network;
    private ConnectionChangeReceiver mReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sku_list);
        util = new BuyUtil(this);
        ocoffee_top_right = (ImageView) findViewById(R.id.ocoffee_top_right);
        ocoffee_top_left = (ImageView) findViewById(R.id.ocoffee_top_left);
        sku_address_tv = (TextView) findViewById(R.id.sku_address_tv);
        sku_list_network_img = (ImageView) findViewById(R.id.frush_img);
        home_network = (RelativeLayout) findViewById(R.id.home_network);
        home_network.setAlpha(0.7f);
        home_network.setOnClickListener(this);
        sku_list_network_img.setOnClickListener(this);
        ocoffee_top_right.setOnClickListener(this);
        ocoffee_top_left.setOnClickListener(this);
        listView = (PullToRefreshListView) findViewById(R.id.store_list);
        listView.setPullToRefreshEnabled(false);
        Utils.startLocationClientAddress(this, mHandler);
        registerReceiver();
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    private void getData(Double u_lat, Double u_lon) {

        if (!MyApplication.isNetworkAvailable(this)) {
            showDialog();
            listView.setVisibility(View.GONE);
            sku_list_network_img.setVisibility(View.VISIBLE);
            new Thread() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(2000);
                        dismissDialog();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }.start();
        } else {
            // final double[] coordinates = util.getCoordinates();
            HttpLoader<SkuListResult> loder = new HttpLoader<SkuListResult>(
                    this, XLGConstants.URL + "Index-storeList",
                    SkuListResult.class);
            AjaxParams params = new AjaxParams();
            params.put(
                    "token",
                    XLGDataUtils.encrypt2MD5("Index" + XLGConstants.SECRET
                            + "storeList"));
            params.put("u_lat", String.valueOf(u_lat));
            params.put("u_lon", String.valueOf(u_lon));
            loder.loadData(params);
            loder.setManagerListener(new OnWebLoadListener<SkuListResult>() {

                @Override
                public void OnStart() {

                }

                @Override
                public void OnError(String error) {
                    listView.setVisibility(View.GONE);
                    sku_list_network_img.setVisibility(View.VISIBLE);
                    dismissDialog();
                }

                @Override
                public void onSuccess(SkuListResult t) {
                    dismissDialog();
                    if (t != null && "000000".equals(t.getCode())) {
                        listView.setVisibility(View.VISIBLE);
                        sku_list_network_img.setVisibility(View.GONE);
                        SkuInfo result = t.getResult();
                        SkuListAdapter adapter = new SkuListAdapter(result,
                                ChoessSKUListActivity.this);
                        listView.setAdapter(adapter);
                    }
                }
            });
        }


    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ocoffee_top_right:
                MyApplication.setIs_skulist_enter_capture(1);
                MyApplication.getInstance().setSkulist_activity(this);
                Intent ewmIntent = new Intent(ChoessSKUListActivity.this,
                        CaptureActivity.class);
                startActivity(ewmIntent);
                break;
            case R.id.ocoffee_top_left:
                Utils.startLocationClientAddress(ChoessSKUListActivity.this,
                        mHandler);
                break;
            case R.id.frush_img:
                Utils.startLocationClientAddress(this, mHandler);
                break;
            case R.id.home_network:
                MyApplication.openSystemSetting(this);
                break;
            default:
                break;
        }
    }

    @Override
    public void onLocationChanged(AMapLocation loc) {
        if (null != loc) {
            Message msg = mHandler.obtainMessage();
            msg.obj = loc;
            msg.what = Utils.MSG_LOCATION_FINISH;
            mHandler.sendMessage(msg);
        }
    }

    /**
     * 注册广播
     */
    private void registerReceiver() {
        IntentFilter filter = new IntentFilter(
                ConnectivityManager.CONNECTIVITY_ACTION);
        mReceiver = new ConnectionChangeReceiver();
        this.registerReceiver(mReceiver, filter);
    }

    public class ConnectionChangeReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {

            ConnectivityManager connectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mobNetInfo = connectivityManager
                    .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
            NetworkInfo wifiNetInfo = connectivityManager
                    .getNetworkInfo(ConnectivityManager.TYPE_WIFI);

            if (!mobNetInfo.isConnected() && !wifiNetInfo.isConnected()) {
                home_network.setVisibility(View.VISIBLE);
            } else {
                home_network.setVisibility(View.GONE);
            }


        }
    }
}
